from django import forms
from django.contrib.auth import get_user_model
from .models import CaptchaModel

User = get_user_model()

class RegisterForm(forms.Form):
    username = forms.CharField(max_length=20,min_length=2,
                               error_messages={'required':'请输入用户名',
                                               'max_length':'用户名长度在2-20',
                                               'min_length':'用户名长度在2-20'})
    email = forms.EmailField(error_messages={'required':'请输入邮箱','invalid':'请输入一个有效的邮箱格式'})

    captcha = forms.CharField(max_length=4,min_length=4,error_messages={'required':'请输入验证码',
                                                                         'max_length':'请输入长度为4的验证码',
                                                                         'min_length':'请输入长度为4的验证码'})
    password1 = forms.CharField(max_length=20,min_length=6,error_messages={'required':'请输入密码',
                                                                           'max_length': '密码长度在6-20',
                                                                           'min_length': '密码长度在6-20'
                                                                           })
    password2 = forms.CharField(max_length=20, min_length=6, error_messages={'required': '请确认密码',
                                                                             'max_length': '密码长度在6-20',
                                                                             'min_length': '密码长度在6-20'
                                                                             })
    def clean_email(self):
        email = self.cleaned_data.get('email')
        exists = User.objects.filter(email=email).exists()
        if exists:
            raise forms.ValidationError("邮箱已经被注册!")
        return email

    def clean_captcha(self):
        captcha = self.cleaned_data.get('captcha')
        email = self.cleaned_data.get('email')
        captcha_model = CaptchaModel.objects.filter(email=email,captcha=captcha).first()
        if not captcha_model:
            raise forms.ValidationError("验证码或邮箱错误")
        captcha_model.delete()
        return captcha


    def clean_password(self):
        passowrd1 = self.cleaned_data.get('password1')
        passowrd2 = self.cleaned_data.get('password2')
        if passowrd1 != passowrd2:
            raise forms.ValidationError("两次密码不匹配")
        return passowrd1

class LoginForm(forms.Form):
    email = forms.EmailField(error_messages={'required': '请输入邮箱', 'invalid': '请输入一个有效的邮箱格式'})
    password = forms.CharField(max_length=20, min_length=6, error_messages={'required': '请输入密码',
                                                                             'max_length': '密码长度在6-20',
                                                                             'min_length': '密码长度在6-20'
                                                                             })
    remember = forms.IntegerField(required=False)